<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Member;
use app\admin\model\Product;
use app\admin\model\Image;

use think\Request;

class Productcomment extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
        $this->defaultOrder = 'create_date DESC';
    }

    public function index(){

        return parent::index();
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            $item['account_number'] = Member::where(['id' => $item['member_id']])->value('account_number');
            $item['product_name'] = Product::where(['id' => $item['product_id']])->value('name');
            // 评论图片
            $imgUrls = Image::where(['related_id' => $item['id']])->order('sorting ASC')->select();
            $item['img_urls'] = $imgUrls;
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['account_number']) && $param['account_number']){
            $memberIds = Member::where(['account_number' => ['like', '%'.$param['account_number'].'%']])->column('id');
            $where['member_id'] = ['in', $memberIds];
        }

        return $where;
    }

    /**
     * 默认条件
     */
    public function getDefaultWhere(){
        $defaultWhere = [
            'product_id' => ['neq', '']
        ];

        return $defaultWhere;
    }

    /**
     * 回复
     */
    public function respond(Request $request){
        $model = model($this->model);
        $data = $request->param();

        $data['member_id'] = $this->admin->id;
        $result = $model->save($data);
        $logInfo = $this->admin->name . '回复了一条' . lang($this->model) . '数据。';
        $afterAction = '_after_insert';

        if($result !== false) {
            // Query执行后的操作
            $model->$afterAction($data);

            // 写入日志
            Common::adminLog($request, $logInfo);

            return $this->success('回复成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error($model->getError());
        }
    }

}